package com.wmh.baseservice.merchant.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.*;
import com.wmh.baseservice.common.utils.encrypt.Base64Util;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantGoods;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.skd.pojo.SkdGoodsSpec;
import com.wmh.baseservice.merchant.service.MerchantGoodsService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.system.pojo.SysCategory;
import com.wmh.baseservice.system.service.SysCategoryService;
import com.wmh.baseservice.user.pojo.UsAddress;
import com.wmh.baseservice.user.pojo.UsAfterSaleApply;
import com.wmh.baseservice.user.pojo.UsGoodsOrder;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsAddressService;
import com.wmh.baseservice.user.service.UsAfterSaleApplyService;
import com.wmh.baseservice.user.service.UsGoodsOrderService;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author wmh generator
 * @since 2022-01-19
 */
@Api(tags = "商家端-普通商品相关接口")
@RestController
@RequestMapping(value = "merchant/merchantGoods", produces = "text/plain;charset=utf-8")
@RequiresRoles("merchant")
@RequiresPermissions(logical = Logical.OR, value = {"商单管理操作", "所有权限"})
public class MerchantGoodsController {

    @Resource
    private MerchantGoodsService merchantGoodsService;
    @Resource
    private SysCategoryService sysCategoryService;
    @Resource
    private UsGoodsOrderService usGoodsOrderService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private UsAddressService usAddressService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private SkdGoodsSpecService merchantSpecService;
    @Resource
    private UsAfterSaleApplyService usAfterSaleApplyService;


    @ApiOperation("list")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String list(PageInfo pageInfo, String name, Long categoryId) {
        Long id = (Long) request.getAttribute("id");
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<MerchantGoods> pageResult = new PageUtil<MerchantGoods>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(MerchantGoods.MERCHANT_ID, id);
            if (CommUtil.checkNull(name)) {
                queryWrapper.like(MerchantGoods.TITLE, name);
            }
            if (CommUtil.checkNull(categoryId)) {
                queryWrapper.eq(MerchantGoods.CATEGORY_ID, categoryId);
            }
            merchantGoodsService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            SysCategory sysCategory = sysCategoryService.getByIdForUpdate(item.getCategoryId());
            if (CommUtil.checkNull(sysCategory)) {
                item.setCategoryName(sysCategory.getName());
            }
        });
        return ReturnBody.success(pageResult);
    }

//    @ApiOperation("添加商品")
//    @PostMapping("addGoods")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
//    })
//    @ParameterVerify(notNull = {"title", "categoryId", "avatar", "overview", "content", "price", "inventory", "hasSpec"})
//    public String addGoods(String title, Long categoryId, String avatar, String img, String overview, String content, MultipartFile video, Integer inventory, Long urlId, BigDecimal price
//            , Integer hasSpec, String specList) {
//        Long id = (Long) request.getAttribute("id");
//        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
//        if (merchantInfo.getParentId() != -1) {
//            MerchantInfo parentInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
//            id = parentInfo.getId();
//        }
//        List<SkdGoodsSpec> skdGoodsSpecList = new ArrayList<>();
//        if (hasSpec == 1) {
//            if (!CommUtil.checkNull(specList)) {
//                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//            }
//            JSONArray array = JSONArray.parseArray(specList);
//            array.forEach(item -> {
//                JSONObject object = JSONObject.parseObject(item.toString());
//                Integer score = object.getInteger("score");
//                BigDecimal discountPrice = object.getBigDecimal("price");
//                BigDecimal originPrice = object.getBigDecimal("originPrice");
//                String describe = object.getString("describe");
//                SkdGoodsSpec skdGoodsSpec = new SkdGoodsSpec().setInventory(score).setOriginPrice(originPrice).setPrice(discountPrice).setDescription(describe);
//                skdGoodsSpecList.add(skdGoodsSpec);
//            });
//        }
//        JSONArray imgList = new JSONArray();
//        MerchantGoods merchantGoods = new MerchantGoods().setTitle(title).setCategoryId(categoryId).setOverview(overview).setContent(content).setInventory(inventory).setUrlId(urlId).setPrice(price).setMerchantId(id);
//        if (!CommUtil.checkNull(urlId)) {
//            urlId = UUIDUtil.getTimeId();
//            merchantGoods.setUrlId(urlId);
//        }
//        if (CommUtil.checkNull(avatar) && avatar.contains("base64")) {
//            String url = Base64Util.generateImage("goodsM/" + urlId, avatar);
//            if (!CommUtil.checkNull(url)) {
//                return ReturnBody.error("图片上传错误");
//            }
//            merchantGoods.setAvatar(url);
//        }
//        if (CommUtil.checkNull(img)) {
//            JSONArray array = JSONArray.parseArray(img);
//            Long finalUrlId = urlId;
//            array.forEach(item -> {
//                String itemImg = Base64Util.generateImage("goodsM/" + finalUrlId, item.toString());
//                if (!CommUtil.checkNull(itemImg)) {
//                    throw new ServiceException("图片上传错误");
//                }
//                imgList.add(itemImg);
//            });
//            merchantGoods.setImg(imgList.toJSONString());
//        }
//        if (CommUtil.checkNull(video)) {
//            String upload = FileUtil.upload("goodsM/" + urlId, video, "file");
//            if (CommUtil.checkNull(upload)) {
//                merchantGoods.setVideo(upload);
//            }
//        }
//        merchantGoods.setHasSpec(hasSpec);
//        merchantGoodsService.add(merchantGoods, skdGoodsSpecList);
//
//        return ReturnBody.success();
//    }

//    @ApiOperation("修改商品")
//    @PostMapping("updateGoods")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
//    })
//    @ParameterVerify(notNull = {"id", "title", "categoryId", "avatar", "overview", "content", "price", "inventory", "hasSpec"})
//    public String updateGoods(Long id, String title, Long categoryId, String avatar, String img, String overview, String content, MultipartFile video, Integer inventory, BigDecimal price, boolean hasVideo
//            , Integer hasSpec, String specList) {
//        MerchantGoods merchantGoods = merchantGoodsService.getByIdForUpdate(id);
//        if (!CommUtil.checkNull(merchantGoods)) {
//            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//        }
//        Long merchantId = (Long) request.getAttribute("id");
//        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(merchantId);
//        if (merchantInfo.getParentId() != -1) {
//            MerchantInfo parentInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
//            merchantId = parentInfo.getId();
//            if (!merchantId.equals(merchantGoods.getMerchantId())) {
//                return ReturnBody.error(ResultCodeInfo.NO_AUTHORITY_OPERATE_PERMISSION);
//            }
//        }
//
//        List<SkdGoodsSpec> skdGoodsSpecList = new ArrayList<>();
//        if (hasSpec == 1) {
//            if (!CommUtil.checkNull(specList)) {
//                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//            }
//            JSONArray array = JSONArray.parseArray(specList);
//            array.forEach(item -> {
//                JSONObject object = JSONObject.parseObject(item.toString());
//                Integer score = object.getInteger("score");
//                BigDecimal discountPrice = object.getBigDecimal("price");
//                BigDecimal originPrice = object.getBigDecimal("originPrice");
//                String describe = object.getString("describe");
//                SkdGoodsSpec skdGoodsSpec = new SkdGoodsSpec().setInventory(score).setOriginPrice(originPrice).setPrice(discountPrice).setDescription(describe);
//                skdGoodsSpecList.add(skdGoodsSpec);
//            });
//        }
//        //1.主图处理
//        if (CommUtil.checkNull(avatar)) {
//            if (avatar.contains("base64")) {
//                FileUtil.delete(merchantGoods.getAvatar());
//                String url = Base64Util.generateImage("goodsM/" + merchantGoods.getUrlId(), avatar);
//                if (!CommUtil.checkNull(url)) {
//                    return ReturnBody.error("图片上传错误");
//                }
//                merchantGoods.setAvatar(url);
//            } else {
//                merchantGoods.setAvatar(avatar);
//            }
//        }
//
//        //2.轮播图处理
//        JSONArray imgArray = new JSONArray();
//        if (CommUtil.checkNull(img)) {
//            //2.1如果图片列表包含base64新上传的编码，则遍历每一个，如果是路径，取出放在上面的数组中，如果是base64，则保存后再存入数组
//            JSONArray array = JSONArray.parseArray(img);
//            array.forEach(item -> {
//                String url = String.valueOf(item);
//                if (url.contains("base64")) {
//                    url = Base64Util.generateImage("goodsM/" + merchantGoods.getUrlId(), item.toString());
//                    if (!CommUtil.checkNull(url)) {
//                        throw new ServiceException("图片上传错误");
//                    }
//                }
//                imgArray.add(url);
//            });
//            //比较然后判断
//            if (CommUtil.checkNull(merchantGoods.getImg())) {
//                List<String> list = FileUtil.getList(merchantGoods.getImg(), imgArray);
//                if (list.size() != 0) {
//                    list.forEach(item -> FileUtil.delete(item));
//                }
//            }
//            merchantGoods.setImg(imgArray.toJSONString());
//        }
//        //2.2轮播图为空设置为null保证修改的时候可上传
//        if (!CommUtil.checkNull(img) || img.equals("[\"\"]")) {
//            merchantGoods.setImg(null);
//        }
//
//        //3.视频处理
//        if (CommUtil.checkNull(video)) {
//            //3.1删除之前的视频
//            if (CommUtil.checkNull(merchantGoods.getVideo())) {
//                FileUtil.delete(merchantGoods.getVideo());
//            }
//            String upload = FileUtil.upload("goodsM/" + merchantGoods.getUrlId(), video, "file");
//            if (CommUtil.checkNull(upload)) {
//                merchantGoods.setVideo(upload);
//            }
//        } else {
//            //3.4没有视频,如果之前有视频则删除视频文件
//            if (CommUtil.checkNull(merchantGoods.getVideo()) && !hasVideo) {
//                FileUtil.delete(merchantGoods.getVideo());
//                merchantGoods.setVideo(null);
//            }
//        }
//        //3.2比较前后html是否一致
//        if (CommUtil.checkNull(content)) {
//            List<String> imgList = FileUtil.getImgElementList(merchantGoods.getContent(), content);
//            if (imgList.size() != 0) {
//                //3.3删除富文本删除的图片
//                imgList.forEach(item -> FileUtil.delete(item));
//            }
//            merchantGoods.setContent(content);
//        }
//
//        //4.对剩下的参数进行赋值
//        merchantGoods.setTitle(title).setCategoryId(categoryId).setOverview(overview).setInventory(inventory).setPrice(price);
//        merchantGoodsService.updateGoods(merchantGoods, skdGoodsSpecList);
//        return ReturnBody.success();
//    }

//    @ApiOperation("商品详情")
//    @PostMapping("goodsDetail")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = true),
//    })
//    public String goodsDetail(Long id) {
//        JSONObject object = new JSONObject(true);
//        MerchantGoods merchantGoods = merchantGoodsService.getByIdForUpdate(id);
//        if (!CommUtil.checkNull(merchantGoods)) {
//            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//        }
//        object.put("merchantGoods", merchantGoods);
//        if (merchantGoods.getHasSpec() == 1) {
//            List<SkdGoodsSpec> merchantSpecs = merchantSpecService.listForUpdate(new QueryWrapper<SkdGoodsSpec>().eq(SkdGoodsSpec.GOODS_ID, merchantGoods.getId()).eq(SkdGoodsSpec.TYPE, 1));
//            object.put("specList", merchantSpecs);
//        }
//        return ReturnBody.success(object);
//    }

    @ApiOperation("删除商品")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"id"})
    public String delete(Long id) {
        MerchantGoods merchantGoods = merchantGoodsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantGoods)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        Long merchantId = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(merchantId);
        if (merchantInfo.getParentId() != -1) {
            MerchantInfo parentInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            merchantId = parentInfo.getId();
            if (!merchantId.equals(merchantGoods.getMerchantId())) {
                return ReturnBody.error(ResultCodeInfo.NO_AUTHORITY_OPERATE_PERMISSION);
            }
        }
        if (!merchantGoodsService.removeById(merchantGoods)) {
            throw new ServiceException();
        }
        File file = new File(PathUtil.getFullRealPath() + "goodsM/" + merchantGoods.getUrlId());
        //删除图片
        if (file.exists()) {
            FileUtil.deleteAllFiles(file);
            if (file.exists()) {
                LogUtil.error("商品图片文件夹删除失败");
            } else {
                LogUtil.info("商品图片文件夹删除成功!");
            }
        } else {
            LogUtil.error("商品图片文件夹不存在");
        }
        return ReturnBody.success();
    }

    @ApiOperation("上下架商品")
    @PostMapping("upOrDown")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String upOrDown(Long id) {
        MerchantGoods merchantGoods = merchantGoodsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantGoods)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        Long merchantId = (Long) request.getAttribute("id");
        CheckUtil.merchantCheck(merchantId, merchantGoods.getMerchantId());
        merchantGoods.setStatus(merchantGoods.getStatus() == 0 ? -1 : 0);
        if (!merchantGoodsService.updateById(merchantGoods)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("图片上传")
    @PostMapping("uploadImg")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String uploadImg(MultipartFile[] file, Long urlId) {
        JSONObject object = new JSONObject();
        Long timeId = 0L;
        //生成随机id文件夹
        if (CommUtil.checkNull(urlId)) {
            timeId = urlId;
        } else {
            timeId = UUIDUtil.getTimeId();
        }
        List<String> uploads = FileUtil.uploads("goodsM/" + timeId, file, "file");
        if (!CommUtil.checkNull(uploads)) {
            return ReturnBody.error("图片上传错误");
        }
        //返回随机id，前端添加商品时传给数据库存储该文件夹字段，方便后面删除商品的时候把图片一起删除
        object.put("uploads", uploads);
        object.put("id", timeId);
        return ReturnBody.success(object);
    }

    @ApiOperation("删除图片")
    @PostMapping("deleteImg")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String deleteImg(String array) {
        JSONArray jsonArray = JSONArray.parseArray(array);
        jsonArray.forEach(item -> {
            FileUtil.delete(item.toString());
        });
        return ReturnBody.success();
    }


    @ApiOperation("列表")
    @PostMapping("orderList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String list(PageInfo pageInfo, String orderNum, Long usId, Integer status) {
        Long id = (Long) request.getAttribute("id");
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsGoodsOrder> pageResult = new PageUtil<UsGoodsOrder>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(orderNum)) {
                queryWrapper.eq(UsGoodsOrder.ORDER_NUM, orderNum);
            }
            if (CommUtil.checkNull(usId)) {
                queryWrapper.eq(UsGoodsOrder.US_ID, usId);
            }
            if (CommUtil.checkNull(status)) {
                queryWrapper.eq(UsGoodsOrder.STATUS, status);
            }
            queryWrapper.eq(UsGoodsOrder.MERCHANT_ID, id);
            queryWrapper.eq(UsGoodsOrder.TYPE, 2);
            queryWrapper.select(UsGoodsOrder.getFields(UsGoodsOrder.SNAPSHOT));
            usGoodsOrderService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String detail(Long id) {
        JSONObject object = new JSONObject(true);
        UsGoodsOrder usGoodsOrder = usGoodsOrderService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(usGoodsOrder)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        UsAddress usAddress = usAddressService.getByIdForUpdate(usGoodsOrder.getAddressId());
        if (CommUtil.checkNull(usAddress)) {
            object.put("address", usAddress);
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usGoodsOrder.getUsId());
        if (CommUtil.checkNull(usInfo)) {
            object.put("nick", usInfo.getNick());
            object.put("avatar", usInfo.getAvatar());
        }
        object.put("goodsOrder", usGoodsOrder);
        //是否有售后
        List<UsAfterSaleApply> usAfterSaleApplies = usAfterSaleApplyService.listForUpdate(new QueryWrapper<UsAfterSaleApply>().eq(UsAfterSaleApply.ORDER_NUM, usGoodsOrder.getOrderNum()));
        if (usAfterSaleApplies.size() != 0) {
            usAfterSaleApplies.sort(Comparator.comparing(UsAfterSaleApply::getCreateTime).reversed());
            object.put("afterSale", usAfterSaleApplies.get(0));
        }
        return ReturnBody.success(object);
    }

    @ApiOperation("发货")
    @PostMapping("delivery")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String delivery(Long id, String expressNumber, Integer type) {
        Long merchantId = (Long) request.getAttribute("id");
        UsGoodsOrder usGoodsOrder = usGoodsOrderService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(usGoodsOrder)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        CheckUtil.merchantCheck(merchantId, usGoodsOrder.getMerchantId());
        if (usGoodsOrder.getStatus() != 1) {
            return ReturnBody.error("状态错误");
        }
        usGoodsOrder.setStatus(2);
        if (type == 1) {
            if (!CommUtil.checkNull(expressNumber)) {
                return ReturnBody.error("快递单号不可为空");
            }
            usGoodsOrder.setExpressNumber(expressNumber);
        }
        usGoodsOrderService.delivery(usGoodsOrder);
        return ReturnBody.success();
    }

    @ApiOperation("获取店铺信息")
    @PostMapping("getMerchantInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String getMerchantInfo() {
        JSONObject object = new JSONObject(true);
        Long id = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (merchantInfo.getParentId() != -1) {
            MerchantInfo parentMerchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            object.put("storeName", parentMerchantInfo.getStoreName());
            object.put("storeAvatar", parentMerchantInfo.getStoreAvatar());
        } else {
            object.put("storeName", merchantInfo.getStoreName());
            object.put("storeAvatar", merchantInfo.getStoreAvatar());
        }
        return ReturnBody.success(object);
    }

    @ApiOperation("修改店铺信息")
    @PostMapping("updateStore")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String updateStore(String storeName, String storeAvatar) {
        Long id = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (merchantInfo.getParentId() != -1) {
            return ReturnBody.error("只有申请人才可修改店铺信息哦");
        }
        String avatar = Base64Util.generateImage("goods/", storeAvatar);
        if (!CommUtil.checkNull(avatar)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        merchantInfo.setStoreAvatar(avatar);
        merchantInfo.setStoreName(storeName);
        if (!merchantInfoService.updateById(merchantInfo)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("审核售后单")
    @PostMapping("auditAfterSale")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "售后订单id", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "status", value = "1同意 -1拒绝", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "address", value = "收件地址", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "refusedReason", value = "拒绝原因", required = false),
    })
    @ParameterVerify(notNull = {"status", "id"})
    public String auditAfterSale(Long id, Integer status, String address, String refusedReason) {
        UsAfterSaleApply usAfterSaleApply = usAfterSaleApplyService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(usAfterSaleApply)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (usAfterSaleApply.getStatus() != 0) {
            return ReturnBody.error("审核状态错误");
        }
        if (usAfterSaleApply.getRefundType() == 2) {
            //退货退款同意下收件地址为必填，用户端售后详情页面要回显商家的地址
            if (!CommUtil.checkNull(address)&&status==1) {
                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
            }
            usAfterSaleApply.setRefundAddress(address);
        }
        if (status == 1) {
            //退货退款类型下修改状态为待寄回
            if (usAfterSaleApply.getRefundType() == 2) {
                usAfterSaleApply.setStatus(1);
            } else {
                //直接退款类型下金额直接原路退回
                usAfterSaleApply.setStatus(2);
            }
        }else if (status == -1) {
            if(!CommUtil.checkNull(refusedReason)){
                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
            }
            usAfterSaleApply.setStatus(-1);
            usAfterSaleApply.setRefusedReason(refusedReason);
        }
        usAfterSaleApplyService.auditAfterSale(usAfterSaleApply);
        return ReturnBody.success();
    }

    @ApiOperation("确认退货")
    @PostMapping("confirmedReturn")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "售后单id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String confirmedReturn(Long id) {
        UsAfterSaleApply usAfterSaleApply = usAfterSaleApplyService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(usAfterSaleApply)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if(usAfterSaleApply.getStatus()!=1){
            return ReturnBody.error("售后单状态错误");
        }
        usAfterSaleApply.setStatus(2);
        usAfterSaleApplyService.confirmedReturn(usAfterSaleApply);
        return ReturnBody.success();
    }

}
